package fi.foyt.cs.persistence.dao.user;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.user.UserIdentifier;

public class UserIdentifierDAO extends GenericDAO<UserIdentifier> {
  
  public UserIdentifier create(Long userId, String identifier) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      UserIdentifier userIdentifier = new UserIdentifier();
      userIdentifier.setIdentifier(identifier);
      userIdentifier.setUserId(userId);
      entityManager.persist(userIdentifier);
      entityManager.getTransaction().commit();
      return userIdentifier;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public UserIdentifier findByIdentifier(String identifier) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select u from UserIdentifier u where identifier = :identifier");
    query.setParameter("identifier", identifier);
    return getSingleResult(query);
  }
  
  @SuppressWarnings("unchecked")
  public List<UserIdentifier> listByUserId(Long userId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from UserIdentifier o where userId = :userId");
    query.setParameter("userId", userId);
    return query.getResultList();
  }
}
